import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '../router'

const request = axios.create({
    baseURL: 'http://localhost:8080',
    timeout: 5000,
    withCredentials: true
})

// 请求拦截器
request.interceptors.request.use(
    config => {
        // 不需要携带 token 的白名单接口
        const noTokenUrls = ['/user/login', '/question/listQuestionsByQid', '/user/qlogin', '/answer/addAnswer']

        // 检查当前请求 URL 是否匹配白名单
        const isWhiteListed = noTokenUrls.some(url => config.url.startsWith(url))

        if (!isWhiteListed) {
            // 从localStorage获取token
            const token = localStorage.getItem('token')
            if (token) {
                console.log('请求携带token:', token)
                config.headers['token'] = `${token}`
            }
        } else {
            console.log('token',localStorage.getItem('token'))
            console.log('跳过 token 注入:', config.url)
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
request.interceptors.response.use(
    response => {
        // 直接返回原始响应，让各个组件自行处理数据
        return response
    },
    error => {
        if (error.response && error.response.status === 401) {
            ElMessage.error('登录已过期，请重新登录')
            localStorage.removeItem('token')
            router.push('/')
        } 
        else {
            ElMessage.error(error.message || '请求失败')
        }
        return Promise.reject(error)
    }
)

export default request